package com.xudu.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.server.HttpServerResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xudu.entity.User;
import com.xudu.mapper.UserMapper;
import com.xudu.service.IUserService;
import com.xudu.utils.Jwt;
import com.xudu.utils.Resoult;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: UserService
 * Description:
 *
 * @Author xudu
 * @Create 2024/4/8
 */

/**
 * 1、实现业务层的接口 alt+enter
 * 2、调用mapper层接口和方法
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    /**
     * 调用mapper层
     */
    @Autowired
    private UserMapper userMapper;

    /**
     * 登陆方法，获取token
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public Resoult login(String username, String password) {


        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);

        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            //代表用户名不存在
            //return new Resoult(1000, "用户不存在" , null);
            return Resoult.error("用户不存在！");
        } else {
            if (user.getPassword().equals(password)) {
                //return new Resoult(1001, "登陆成功" , user);
                Map<String, String> map = new HashMap<>();
                map.put("username",user.getUsername());
                //基于jwt 生成token
                String token = Jwt.create(map);

                //返回用户数据和token
                return Resoult.success(user, token);
            } else {
                //代表密码错误
                //return new Resoult(1002, "密码错误" , null);
                return Resoult.error("密码错误！");
            }
        }
    }


    /**
     * 注册用户
     *
     * @param user
     * @return
     */
    @Override
    public Resoult register(User user) {
        userMapper.insert(user);
        return Resoult.success();
    }


    /**
     * 添加用户，需要上传图片，图片保存路径保存在数据库中
     *
     * @param username
     * @param password
     * @param photo
     * @return
     */
    @SneakyThrows
    @Override
    public Resoult saveUserWithPhoto(String username, String password, MultipartFile photo) {

        //防止用户名重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        if (username.equals(user.getUsername())){
            return Resoult.error("用户名重复！");
        }


        // 设置文件存储路径
        String FILE_DIRECTORY = "E:/upload/";
        //File.separator相当于“\”
        //获得文件存储路径
        String filePath = FILE_DIRECTORY + photo.getOriginalFilename();

        // 保存文件在指定路径
        photo.transferTo(new File(filePath));

        //将前端数据保存到数据库中
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        newUser.setImgPath(filePath);
        userMapper.insert(newUser);


        return Resoult.success();
    }


    @Override
    public InputStream getPhoto(String path) throws FileNotFoundException {
        File file = new File(path);
        return new FileInputStream(file);
    }


    // 通过用户名获取用户照片
    @Override
    public void getUserPhoto(String username, HttpServletResponse response) throws IOException {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);

        File photoFile = new File(user.getImgPath());
        byte[] bytes = FileUtil.readBytes(photoFile);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();

    }


}
